package per.turtle.common.excel.converters;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.excel.converters.Converter;
import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.metadata.GlobalConfiguration;
import com.alibaba.excel.metadata.data.ReadCellData;
import com.alibaba.excel.metadata.data.WriteCellData;
import com.alibaba.excel.metadata.property.ExcelContentProperty;

import java.util.Arrays;

/**
 * 是与否
 *
 * @author turtle
 */
public class BooleanStringConverter implements Converter<Boolean> {

    private static final String[] TRUE_STR = {"TRUE", "T", "Y", "是"};

    private static final String[] FALSE_STR = {"FALSE", "F", "N", "否"};

    @Override
    public Class<Boolean> supportJavaTypeKey() {
        return Boolean.class;
    }

    @Override
    public CellDataTypeEnum supportExcelTypeKey() {
        return CellDataTypeEnum.STRING;
    }

    @Override
    public Boolean convertToJavaData(ReadCellData cellData, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) {
        if (CollectionUtil.contains(Arrays.asList(TRUE_STR), cellData.getStringValue().toUpperCase())) {
            return true;
        } else if (CollectionUtil.contains(Arrays.asList(FALSE_STR), cellData.getStringValue().toUpperCase())) {
            return false;
        } else {
            return null;
        }
    }

    @Override
    public WriteCellData<String> convertToExcelData(Boolean value, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) {
        if (value == null) {
            return new WriteCellData<>("");
        } else if (value) {
            return new WriteCellData<>("是");
        } else {
            return new WriteCellData<>("否");
        }
    }

}
